<template>
  <el-form-item prop="captcha">
    <div class="captcha">
      <el-input
          class="text"
          v-model="localCaptcha"
          prefix-icon="Picture"
          placeholder="请输入验证码"
      ></el-input>
      <img :src="captchaSrc" @click="refreshCaptcha" />
    </div>
  </el-form-item>
</template>

<script>
import { defineComponent, reactive, watch, toRefs, ref } from 'vue'
import { GetValidateCode } from '@/api/login'

export default defineComponent({
  name: 'CaptchaInput',
  props: {
    modelValue: {  // 改为使用 modelValue 来接收 v-model 数据
      type: String,
      required: true,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      captchaSrc: '',
    })
    const localCaptcha = ref(props.modelValue)  // 创建本地的 ref 来同步 modelValue

    // 刷新验证码
    const refreshCaptcha = async () => {
      const {data} = await GetValidateCode()
      props.modelValue = data.codeKey  // 更新验证码 codeKey
      state.captchaSrc = data.codeValue  // 更新验证码图片
    }

    // 监听 localCaptcha 的变化，触发 update:modelValue 事件
    watch(localCaptcha, (newValue) => {
      emit('update:modelValue', newValue)  // 通过事件将变化同步给父组件
    })

    // 初始化时刷新验证码
    refreshCaptcha()

    return {
      ...toRefs(state),
      refreshCaptcha,
      localCaptcha, // 曝露 localCaptcha
    }
  },
})
</script>
